<template>
  <el-form :model="form" label-width="120px">
    <el-form-item label="专业名称">
      <el-input v-model="form.major_name" />
    </el-form-item>
    <el-form-item label="所属学院">
      <el-select v-model="form.department_name" @change="handleDepartmentChange">
        <el-option 
          v-for="dept in departments" 
          :key="dept.department_name" 
          :label="dept.department_name" 
          :value="dept.department_name"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="下属班级数">
      <el-input v-model="form.class_number" disabled />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">确认修改</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import MajorApi from '@/api/MajorApi';

export default {
  props: {
    currentMajor: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        major_id: '',  // 添加专业ID字段用于修改
        major_name: '',
        department_id: '',
        department_name: '',  // 用于显示
        class_number: 0
      },
      departments: [] // 学院列表
    };
  },
  methods: {
    submitForm() {
      // 确保department_name是最新的
      const selectedDept = this.departments.find(
        dept => dept.department_id === this.form.department_id
      );
      if (selectedDept) {
        this.form.department_name = selectedDept.department_name;
      }
      
      this.$emit('submit-form', this.form);
    },
    closeDialog() {
      this.$emit('close-dialog');
    },
    handleDepartmentChange(value) {
      this.form.department_id = value;
    },
    async fetchColleges() {
      try {
        const response = await MajorApi.getCollegesForm();
        this.departments = response.data.data || response.data;
      } catch (error) {
        console.error("学院信息获取错误:", error);
        this.$message.error('获取学院信息失败');
      }
    }
  },
  watch: {
    currentMajor: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.form = {
            major_id: newVal.major_id,
            major_name: newVal.major_name,
            department_id: newVal.class_id,
            department_name: newVal.college_name,
            class_number: newVal.class_number || 0
          };
        }
      }
    }
  },
  created() {
    this.fetchColleges();
  }
};
</script>